#include "stdafx.h"
#include "ShareData.h"

using namespace xBase;
using namespace std;

CShareData::CShareData()
    : m_dwStamp(0)
{

}

CShareData::~CShareData()
{

}

bool CShareData::GetData(CopyData& data)
{
    CxAutoLock lock(m_oLock);
    data = m_oData;
    return true;
}

DWORD CShareData::GetStamp()
{
    return m_dwStamp;
}

DWORD CShareData::WriteString(const wstring& wstr)
{
    CxAutoLock lock(m_oLock);
    m_oData.type = E_CDT_WSTRING;
    m_oData.wstr = wstr;
    return _generate_stamp();
}

DWORD CShareData::WriteString(const string& str)
{
    CxAutoLock lock(m_oLock);
    m_oData.type    = E_CDT_STRING;
    m_oData.str     = str;
    DWORD dwRet = _generate_stamp();

    _data_changed();

    return dwRet;
}

BOOL CShareData::RegisterListener(IShareDataListener* pListener)
{
    Listeners::iterator it = std::find(m_vecListners.begin(), m_vecListners.end(), pListener);
    if (it != m_vecListners.end())
    {
        return FALSE;
    }
    else
    {
        m_vecListners.push_back(pListener);
        return TRUE;
    }
}

BOOL CShareData::UnregisterListener(IShareDataListener* pListener)
{
    Listeners::iterator it = std::find(m_vecListners.begin(), m_vecListners.end(), pListener);
    if (it != m_vecListners.end())
    {
        m_vecListners.erase(it);
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

DWORD CShareData::_generate_stamp()
{
    m_dwStamp = ::GetTickCount();
    return m_dwStamp;
}

VOID CShareData::_data_changed()
{
    Listeners::reverse_iterator rit = m_vecListners.rbegin();
    while (rit != m_vecListners.rend())
    {
        xBase::CScopedRefPtr<IShareDataListener> pListener = *rit;
        if (pListener)
        {
            pListener->OnDataChanged(m_dwStamp);
        }
        ++rit;
    }
}
